﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SmartCardClient.Commands
{
	internal static class EventSystem
	{
		#region fields

		private static Dictionary<string, IList<Action<object, EventArgs>>> _eventMap =
				new Dictionary<string, IList<Action<object, EventArgs>>>();

		#endregion

		/// <summary>
		/// Registers the provided event.  name must be unique
		/// </summary>
		/// <param name="eventName"></param>
		public static bool Register(string eventName)
		{
			bool existed = _eventMap.ContainsKey(eventName);

			if (existed)
			{ throw new ArgumentNullException(""); }

			var attached = new List<Action<object, EventArgs>>();
			_eventMap.Add(eventName, attached);

			return existed;
		}

		/// <summary>
		/// Checkes to see if the specified event has already been registered
		/// </summary>
		/// <param name="eventName"></param>
		/// <returns></returns>
		public static bool Registered(string eventName)
		{ return _eventMap.ContainsKey(eventName); }

		/// <summary>
		/// Attaches to the specified event
		/// </summary>
		/// <param name="eventName"></param>
		/// <param name="handler"></param>
		public static void Attach(string eventName, Action<object, EventArgs> handler)
		{
			var handlers = _eventMap[eventName];
			handlers.Add(handler);
		}

		/// <summary>
		/// Detaches from the specified event
		/// </summary>
		/// <param name="eventName"></param>
		/// <param name="handler"></param>
		public static void Detach(string eventName, Action<object, EventArgs> handler)
		{
			var handlers = _eventMap[eventName];
			handlers.Remove(handler);
		}

		public static void Signal(string eventName, object sender, EventArgs eventArgs)
		{
			var handlers = _eventMap[eventName];
			foreach (var handler in handlers)
			{ handler(sender, eventArgs); }
		}
	}
}
